const express = require('express');
const router = express.Router();
const TermService = require('../../service/term');
const _ = require('lodash');

const TermFields = ['_id','term_name','term_slug','term_desc'];

/**
 * 获取分类列表
 */
router.get('/list', function(req, res, next){
  const type = req.query.type || '';
  TermService.getList(type).then( (doc) => {
    return res.json({code: 0, msg: 'success', data: doc});
  }).catch(function (err) {
    return res.json({code: -1, msg: err, data: null})
  });
})

/**
 * 新增分类
 */
router.post('/add', function(req, res, next){
  const options = _.pick(req.body,TermFields);
  TermService.add(options).then( (doc) => {
    return res.json({code: 0, msg: 'success', data: doc});
  }).catch( (err) =>{
    return res.json({code: -1, msg: err, data: null})
  });
});

/**
 * 更新分类信息
 */
router.post('/update', function(req, res, next){
  const options = _.pick(req.body,TermFields);
  TermService.updateInfo(options).then((doc) => {
    return res.json({code: 0, msg: 'success', data: doc});
  }).catch((err)=>{
    return res.json({code: -1, msg: err, data: null})
  })
});


/**
 * 删除分类
 */
router.post('/delete', function(req, res, next){
  TermService.remove(req.body._id).then((doc)=>{
    return res.json({code: 0, msg: 'success', data: doc});
  }).catch((err)=>{
    return res.json({code: -1, msg: err, data: null})
  })
});

module.exports = router;
